package com.changxianggu.crawler.cloud.test;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.changxianggu.cloud.crawler.core.WebApplication;
import com.changxianggu.cloud.crawler.core.modules.storage.entity.CxgBook;
import com.changxianggu.cloud.crawler.core.modules.storage.service.ICxgBookService;
import com.changxianggu.cloud.crawler.core.utils.HttpUtil;
import com.changxianggu.cloud.crawler.core.utils.UserAgentUtil;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {WebApplication.class})// 指定启动类
@Slf4j
public class MaGongCheng {

    @Autowired
    ICxgBookService bookService;

    public static final String COOKIE = "JSESSIONID=ie7032mb0c0b1xewu9jz3rkd2";
    public static final String ORIGIN = "http://data.lilun.cn";
    public static final String REFERER = "http://data.lilun.cn/html/customColumn.html?f9f1930f-f8da-4568-831f-0b5e33f0b9dc";
    public static final String URL_PRE = "http://data.lilun.cn";

    @Test
    public void initCrawler() throws Exception {
        doCrawler();
    }

    public void doCrawler() throws Exception {
        int pageNum = 0;
        int totalPage = 2033;
        int pageSize = 8;
        for (int i = pageNum; i <= totalPage; i++) {
            String url = "http://data.lilun.cn/Service/?logic=bookController&call=getBookByColumn";
            Map<String, Object> parameter = MapUtil.newHashMap(6);
            parameter.put("page", i);
            parameter.put("pageSize", pageSize);
            parameter.put("panel", "custom");
            parameter.put("specialid", "f9f1930f-f8da-4568-831f-0b5e33f0b9dc");
            parameter.put("columnId", "f9f1930f-f8da-4568-831f-0b5e33f0b9dc");
            Map<String, Object> headers = MapUtil.newHashMap(5);
            headers.put("Cookie", COOKIE);
            headers.put("ORIGIN", ORIGIN);
            headers.put("User-Agent", UserAgentUtil.random());
            headers.put("Referer", REFERER);
            String result = HttpUtil.doPost(url, headers, parameter);
            if (StrUtil.isNotBlank(result)) {
                JSONObject jsonObject = JSONObject.parseObject(result);
                JSONObject resultObject = jsonObject.getJSONObject("result");
                if (resultObject != null) {
                    JSONArray listObject = resultObject.getJSONArray("bookinfo");
                    int size = listObject.size();
                    List<CxgBook> listBook = new ArrayList<>();
                    for (int k = 0; k < size; k++) {
                        JSONObject jsonTmp = listObject.getJSONObject(k);
                        CxgBook bookEntity = new CxgBook();
                        bookEntity.setBookName(jsonTmp.getString("bookname"));
                        bookEntity.setAuthor(jsonTmp.getString("author"));
                        bookEntity.setPkId(jsonTmp.getString("bookid"));
                        bookEntity.setBookIsbn(jsonTmp.getString("isbn"));
                        LocalDateTime localDateTime = LocalDateTime.ofEpochSecond(jsonTmp.getLong("releaseDate") / 1000, 0, ZoneOffset.ofHours(8));
                        bookEntity.setPubDate(localDateTime);
                        String digUri = "http://data.lilun.cn/Service/?logic=PDFReaderController" +
                                "&call=readPDF&bookid=" + jsonTmp.getString("bookid") +
                                "&page=1&html=selectText_NOINC&from=online&searchChar=undefined" +
                                "&columnId=f9f1930f-f8da-4568-831f-0b5e33f0b9dc";
                        bookEntity.setDigitalUri(digUri);
                        bookEntity.setIsSync(0);
                        bookEntity.setCreateTime(LocalDateTime.now());
                        bookEntity.setPressName("人民出版社");
                        bookEntity.setStatus(1);
                        //出版社Id不明
                        bookEntity.setPressId(847);
                        listBook.add(bookEntity);
                    }
                    bookService.saveBatch(listBook);
                    log.info("第" + i + "页数据保存成功");
                    log.warn("--->" + i);
                }
            }
        }
    }

    /**
     * 判断一个字符串是否都为数字
     *
     * @param strNum
     * @return
     */
    public boolean isDigit(String strNum) {
        Pattern pattern = Pattern.compile("[0-9]{1,}");
        Matcher matcher = pattern.matcher((CharSequence) strNum);
        return matcher.matches();
    }

    /**
     * 截取数字
     *
     * @param content
     * @return
     */
    public String getNumbers(String content) {
        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher(content);
        while (matcher.find()) {
            return matcher.group(0);
        }
        return "";
    }
}
